package com.example.web;

import com.example.pojo.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();

    /**
     * 注销处理
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.销毁Session中的用户登录的信息（或销毁Session）
        request.getSession().invalidate();
        //2.重定向到首页（或登录页面）
        response.sendRedirect(request.getContextPath());
    }
    /**
     * 登录处理
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User loginUser = userService.login(new User(null, username, password, null));
        if(loginUser == null){
            //把错误信息和回显的表单项放进Request域中
            request.setAttribute("msg", "用户名或密码错误！");
            request.setAttribute("username", username);
            //登录失败跳回登录界面
            System.out.println("登录失败");
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }else {
            //登录成功
            System.out.println("登陆成功");
            //保存用户登录的信息到Session域中
            request.getSession().setAttribute("user",loginUser);
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request, response);
        }
    }

    //验证用户名是否可用
    protected void ajaxExistUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        boolean existUsername = userService.existUsername(username);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existUsername", existUsername);
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        response.getWriter().write(json);

    }

    /**
     * 注册处理
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Session中的验证码
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);


        //  1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");


        User user = WebUtils.copyParamToBean(request.getParameterMap(), new User());

            //  2.检查验证码是否正确 === 先写死，为abcd
            if(token!=null && token.equalsIgnoreCase(code)){
                //正确
                //3.检查用户名是否可用
                if (userService.existUsername(username)){
                    //不可用
                    System.out.println("用户名["+username+"]已存在");
                    //把回显信息放入request域中
                    request.setAttribute("msg", "用户名已存在！");
                    request.setAttribute("username", username);
                    request.setAttribute("email", email);
                    //跳回注册页面    register.jsp
                    request.getRequestDispatcher("/pages/user/register.jsp").forward(request, response);
                }else{
                    //可用
                    //调用Service保存到数据库
                    userService.registerUser(new User(null, username, password, email));
                    //跳到注册成功页面  register_success.jsp
                    request.getRequestDispatcher("/pages/user/register_success.jsp").forward(request, response);
                }
            }else{
                //不正确
                System.out.println("验证码["+code+"]错误");
                //把回显信息放入request域中
                request.setAttribute("msg", "验证码错误！");
                request.setAttribute("username", username);
                request.setAttribute("email", email);
                //跳回注册页面    register.jsp
                request.getRequestDispatcher("/pages/user/register.jsp").forward(request, response);
            }
        }

}
